import * as THREE from 'three';

// 交互管理器模块 - 可复用的3D对象交互逻辑
export class InteractionObj {
    constructor(targetObject, camera, rendererDom) {
        this.target = targetObject;
        this.camera = camera;
        this.dom = rendererDom;
        this.isHovered = false;
        this.raycaster = new THREE.Raycaster();
        this.mouse = new THREE.Vector2();
        this.init();
    }

    init() {
        this.dom.addEventListener('click', this.handleClick.bind(this));
        this.dom.addEventListener('mousemove', this.handleMouseMove.bind(this));
    }

    handleClick(event) {
        this.updateMouse(event);
        this.raycaster.setFromCamera(this.mouse, this.camera);
        const intersects = this.raycaster.intersectObjects([this.target]);
        if (intersects.length > 0) {
            console.log('hit');
        }
    }

    handleMouseMove(event) {
        this.updateMouse(event);
        this.raycaster.setFromCamera(this.mouse, this.camera);
        const intersects = this.raycaster.intersectObjects([this.target]);
        
        if (intersects.length > 0) {
            if (!this.isHovered) {
                console.log('in');
                this.isHovered = true;
            }
        } else {
            if (this.isHovered) {
                console.log('out');
                this.isHovered = false;
            }
        }
    }

    updateMouse(event) {
        this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        this.mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
    }
}